#include"io430.h"
#include"intrinsics.h"
#include"pwm.h"

volatile unsigned char flag_pwm=0;  
volatile short num_impulse=0;
volatile unsigned char flag_impulse=0;


void Init_PWM(unsigned short _x)
{
  P4SEL|=BIT1;
  TBCTL = TASSEL_2 + MC_1;
  TBCCR0 = 160;
  TBCCTL0|=CCIE;
  TBCCR1 = _x;
  TBCCTL1 |= OUTMOD_7;
};



void set_PWM(unsigned short _x)
{
  TBCCR1=_x%160;  
};

void On_LT8410_20V(void)
{
  P4OUT|=BIT0;
};

void Off_LT8410_20V(void)
{
  P4OUT&=~BIT0;
};

void Out_Enable(void)
{
  P4OUT|=1<<7;
};

void Out_Disable(void)
{
  P4OUT&=~(1<<7);
};

void Out_impulse_Disable(void)
{
  P4OUT|=1<<2;
};

void Out_impulse_Enable(void)
{
  P4OUT&=~(1<<2);
};

void On_PWM(unsigned char _ad,unsigned char _p,unsigned short _num_impulse) // addre, current, numer impulse
{
  unsigned short i;
  if (flag_pwm==0)
  {
   if (_num_impulse!=0)
   { 
    flag_impulse=0;
    flag_pwm=0;     
    Out_Disable();
    Out_impulse_Disable();
    On_LT8410_20V();
    for(i=0;i<10;i++) __delay_cycles(8000);
    Init_PWM(_p);
    if (_ad&0x01) P3OUT|=BIT4; else P3OUT&=~BIT4;
    if (_ad&0x02) P3OUT|=BIT5; else P3OUT&=~BIT5;  
    for(i=0;i<500;i++) __delay_cycles(8000);
    Out_Enable();
    num_impulse=(_num_impulse)*50;    
    flag_impulse=1;
   };
   flag_pwm=1;
  };
};

void Off_PWM(void)
{
  P4OUT&=~BIT1;
  P4SEL&=~BIT1;
  TBCTL = MC_0;
  TBCCTL0&=~(CCIE);
  TBCCTL1&=~OUT;
  Out_impulse_Disable();
  Out_Disable();
  Off_LT8410_20V();
  flag_on_pwm=0; 
  flag_run_pwm=0;
};

#pragma vector=TIMERB0_VECTOR
__interrupt void TimerB_ISR (void)
{
  static unsigned short pwm_count=0;
  static unsigned short pwm_count1=0;
  
WDTCTL=WDT_ARST_1000; 
if (flag_impulse==1)
 {
  if (pwm_count1==num_impulse)
   {
    Off_PWM();   
    flag_impulse=0;
    pwm_count1=0;
    pwm_count=0;
    flag_pwm=0;    
    P1OUT&=~BIT2;
    return;
   };
  if (pwm_count==0)  P4OUT&=~BIT2;
//  if (pwm_count==1) P4OUT|=BIT7;
  if (pwm_count==51*2) P4OUT|=BIT2; 
//  if (pwm_count==103) P4OUT&=~BIT7;
  pwm_count++;
  if (pwm_count>490) {pwm_count=0;pwm_count1++;};

  
 };
};
